﻿using QBWeb.Models;
using QBWeb.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JiebaNet.Segmenter.Common;
using QBWeb.Models.QuestionFolder;
using QBWeb.Models.TestFolder;
using QBWeb.Models.CurriculumFolder;

namespace QBWeb.Controllers
{
    /// <summary>
    /// 考试模块控制器类
    /// </summary>
    public class AnswerInfoTbController : Controller
    {
        private readonly QBDbContext db = new QBDbContext();

        /// <summary>
        /// GET: AnswerInfoTb
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return Content("no html view");
            //return View(); //屏蔽错误
        }

        #region 学生考试功能

        //返回所有试卷
        /// <summary>
        /// 返回所有学生试卷
        /// </summary>
        /// <param name="curriculaId"></param>
        /// <returns></returns>
        [Authorize(Roles = "students")]
        public JsonResult ResultAllTestToStu(int curriculaId)
        {
            var str = new List<object>();
            // 查询用户id
            var user = db.UserNameTbs.Where(t => t.NickName == User.Identity.Name).First();
            // 查询用户所在的班级编号
            var classes = new ClassesTb();
            var classList = db.ClassesTbs.Include(t => t.Curriculum).Where(t => t.CurriculumId == curriculaId);
            var classStudent = db.ClassesStudentTbs.Where(t => t.StudentId == user.UserId);
            bool isFind = false;
            foreach (var x in classList)
            {
                foreach (var y in classStudent)
                {
                    if (x.Id == y.ClassesTbId)
                    {
                        classes = x;
                        isFind = true;
                        break;
                    }
                }
                if (isFind) break;
            }
            // 查询班级中的试卷
            var testPapers = db.TestPaperTbs.Include(t => t.Issue).Where(a => a.CurriculaId == curriculaId).Where(a => a.Issue.Status != 0).ToList();
            var testPaper = db.ClassTestPaperTbs.Where(t => t.ClassesTbId == classes.Id);
            var testPaperList = new List<TestPaperTb>();
            foreach (var x in testPapers)
            {
                foreach (var y in testPaper)
                {
                    if (x.IssueId == y.IssueId)
                        testPaperList.Add(x);
                }
            }

            var checkHadTest = 0;
            foreach (var x in testPapers)
            {
                //检查是否答过
                
                var info =
                    db.AnswerRecordTbs.Where(a => a.StudentName == User.Identity.Name && a.TestId == x.Id).ToList();
               //统计分数
               var scoreStr = "--";
               if (info.Count != 0)
                {
                    var score = db.AnswerInfoTbs
                    .Where(a => a.TF == 1 && a.TestPaperTbId == x.Id&&a.UserName == User.Identity.Name)
                    .Sum(b => b.Score);
                    checkHadTest = 1;
                    if (info.First().Status == 1)//判断是否审阅
                    {
                        scoreStr = score.ToString();
                    }
                    
                } 
                str.Add(new
               {
                   hadTest = checkHadTest,
                   testId = x.Id,
                   testName = x.TestName,
                   author = x.Creator,
                   startTime = x.Issue.StartTime.ToString(),
                   endTime = x.Issue.EndTime.ToString(),
                   limitTime = x.Issue.OnTime,
                   status = x.Issue.Status,
                   score = scoreStr
               });
                checkHadTest = 0;
            }
            return Json(str, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 返回考试界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Examination(int id)
        {
            var issues = db.Issues.Find(id);
            if (issues != null)
            {
                var start = issues.StartTime;
                var end = issues.EndTime;
                if (!JudgeTime(start, end))
                {
                    return Content("<p style='text-align:center;font-size:28px'>not allow</p>");
                }
            }
            var paper = new PaperViewModels()
            {
                TestPaperTb = db.TestPaperTbs.First(m => m.IssueId == id),
                Issue = issues,
            };
            ViewData.Model = paper;
            return View("Exam");
        }
        /// <summary>
        /// 判断合法时间区间
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public bool JudgeTime(DateTime? startTime,DateTime? endTime)
        {
            var current = DateTime.Now;
            return startTime <= current && endTime >= current;
        }
        #endregion

        


        /// <summary>
        /// 提交答题答案
        /// </summary>
        /// <param name="testPaperTbId"></param>
        /// <param name="questionTbId"></param>
        /// <param name="answer"></param>
        /// <param name="type"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Examination(int testPaperTbId,int[] questionTbId,string[] answer,int[] type,string[] score)
        {
            var answerRecord = new AnswerRecordTb()
            {
                StudentName = User.Identity.Name,
                TestId = testPaperTbId,
                CreateTime = DateTime.Now,
                Status = 0
            };
            db.AnswerRecordTbs.Add(answerRecord);
           
            for (var i = 0; i < questionTbId.Length; i++)
            {
                AnswerInfoTb answerInfo;
                var correctOrNot = 0;//是否正确
                var questId = questionTbId[i];
                switch (type[i])
                {
                        
                    case 1:
                        var sg = db.SingleChoiceTbs.Single(a => a.QuestionTbId == questId&&a.CorrectOption=="1");
                        if (answer[i].Trim() == sg.Value)
                        {
                            correctOrNot = 1;
                        }
                        //统计分数根据是否正确 求和正确题目的分数
                        answerInfo = new AnswerInfoTb(User.Identity.Name, testPaperTbId, questionTbId[i], answer[i], correctOrNot, Convert.ToInt32(score[i]));
                        db.AnswerInfoTbs.Add(answerInfo);
                        
                        break;
                    case 2:
                        var tf=db.TrueFalseTbs.Single(a => a.QuestionTbId == questId);
                        if (answer[i] == "")
                        {
                            answer[i] = "-1";
                        }

                        if (Convert.ToInt32(answer[i]) == tf.CorrectValue)
                        {
                            correctOrNot = 1;
                        }
                        //统计分数根据是否正确 求和正确题目的分数
                        answerInfo = new AnswerInfoTb(User.Identity.Name, testPaperTbId, questionTbId[i], answer[i], correctOrNot, Convert.ToInt32(score[i]));
                        db.AnswerInfoTbs.Add(answerInfo);
                        break;
                    case 3: //填空题匹配格式暂不处理
                        var bl=db.BlanksTbs.Single(a => a.QuestionTbId == questId);
                        if (answer[i] == bl.CorrectValue)
                        {
                            correctOrNot = 1;
                        }
                        //统计分数根据是否正确 求和正确题目的分数
                        answerInfo = new AnswerInfoTb(User.Identity.Name, testPaperTbId, questionTbId[i], answer[i], correctOrNot, Convert.ToInt32(score[i]));
                        db.AnswerInfoTbs.Add(answerInfo);
                        break;
                }
                
            }
            db.SaveChanges();
            return RedirectToAction("Index","TestPaperTbs");//页面跳转错误，后面调整
        }


        /// <summary>
        /// 教师评阅试卷
        /// </summary>
        /// <returns></returns>
      
        public ActionResult TeacherReviewPaper(int id)
        {
            var list = db.AnswerRecordTbs.Where(a => a.TestId == id).ToList();
            var stuScore = db.AnswerInfoTbs
                .Where(a => a.TestPaperTbId == id&&a.TF==1)
                .Select(n=>new{n.UserName,n.Score})
                .GroupBy(b => b.UserName)
                .Select(c=>new Temp(){UserName = c.FirstOrDefault().UserName,Score =c.Sum(a=>a.Score)})
                .ToList();
            ViewBag.data = stuScore;
            return View(list);
        }
        /// <summary>
        /// 查询单个学生考试情况
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult ReviewPaperDetail(int id,string name)
        {
            var list = db.AnswerInfoTbs.Include(a=>a.QuestionTb)
                .Where(a => a.UserName == name && a.TestPaperTbId == id)
                .Select(item => new AnswerInfoQuest
                {
                    QuestionTb = item.QuestionTb,
                    AnswerInfoTb = item
                }).ToList();
            ViewBag.name = name;
            ViewBag.id = id;
            ViewBag.data2 = list;
            return View();
        }
        public JsonResult EditStatus(int testId,string stuName,int status)
        {
            try
            {
                var res = db.AnswerRecordTbs.Single(a => a.TestId == testId && a.StudentName == stuName);
                res.Status = status;
                db.Entry(res).State = EntityState.Modified;
                db.SaveChanges();
                return Json(new { });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
       /// <summary>
       /// 推荐错题所属类别的其它题
       /// </summary>
        public ActionResult Recommend(int id)
       {
           var list = db.AnswerInfoTbs.Include(x=>x.QuestionTb)
               .Where(a => a.UserName == User.Identity.Name && a.TF == 0 && a.TestPaperTbId == id)
               .ToList();
           var knowList = new List<string>();
           var otherList = new List<string>();
           foreach (var item in list)
           {
               var x = item.QuestionTb.SmallKnowModuleTbId;
               var res = db.SmallKnowModuleTbs.Find(x)?.SmallModuleName;
               knowList.Add(res); 
               var otherQuest = db.QuestionTbs.Where(a => a.SmallKnowModuleTbId == x).ToList();
               otherList.AddRange(otherQuest.Select(s => s.QuestName));
           }

           ViewBag.xData = knowList.Distinct();
           ViewBag.yData =otherList.Distinct();
           return View();
       }

    }

    
    
}